<template>
  <TopNavBar title="提款"  type="back" />

  <div class="withdraw-apply-container">
    <div class="withdraw-tabs">
      <div :class="['tab', activeTab === 0 ? 'active' : '']" @click="activeTab = 0">加密貨幣</div>
      <div :class="['tab', activeTab === 1 ? 'active' : '']" @click="activeTab = 1">法幣</div>
      <!-- <div :class="['tab', activeTab === 2 ? 'active' : '']" @click="activeTab = 2">OTC提現</div> -->
    </div>
    <div v-if="activeTab === 0" class="tab-content">
      <div class="form-item">
        <label class="form-label">網路</label>
        <div class="form-value select-value network-select-trigger" @click="openNetworkSelect">
          {{ selectedNetwork }}
          <svg style="margin-left:auto;" width="18" height="18" viewBox="0 0 24 24"><path d="M7 10l5 5 5-5" stroke="#bbb" stroke-width="2" fill="none"/></svg>
        </div>
      </div>
      <div class="form-item">
        <label class="form-label">幣種</label>
        <div class="form-value coin-value coin-select-trigger" @click="openCoinSelect">
          <img :src="coinOptions.find(c=>c.value===selectedCoin)?.icon" class="coin-icon" alt="coin" />
          {{ selectedCoin }}
          <svg style="margin-left:auto;" width="18" height="18" viewBox="0 0 24 24"><path d="M7 10l5 5 5-5" stroke="#bbb" stroke-width="2" fill="none"/></svg>
        </div>
      </div>
      <div class="form-item">
        <label class="form-label">地址</label>
        <input class="form-input" v-model="address" placeholder="請輸入錢包地址" />
      </div>
      <div class="form-item">
        <label class="form-label">提幣數量</label>
        <div class="input-group">
          <input class="form-input" v-model="amount" placeholder="請輸入提幣數量(0.0001–1,000,000,000)" type="number" min="0.0001" step="0.0001" />
          <button class="all-btn" @click="setAll">全部</button>
        </div>
      </div>
      
      <div class="form-item">
        <label class="form-label">提現密码</label>
        <div class="input-group">
          <input class="form-input" v-model="password" placeholder="" type="number" />
          <!-- <button class="all-btn" @click="setAll">全部</button> -->
        </div>
      </div>
      <div class="info-row">
        <span>提現費用：{{ withdrawType?.ratio }}%</span>
        <span style="margin-left:auto;">可用餘額：{{ allAmount }}</span>
      </div>
      <div class="info-row">
        <span>實際到帳：{{ Number(amount) - Number(amount * withdrawType?.ratio) }}</span>
      </div>
      <div class="submit-btn-section">
        <button class="submit-btn" @click="submit">提交</button>
      </div>
    </div>
    <div v-if="activeTab === 1" class="tab-content">
      <div class="fiat-balance-row">
        <span class="fiat-currency">USD</span>
        <span class="fiat-balance">可提款金額：{{ allAmount }}</span>
      </div>
      <div class="form-item">
        <label class="form-label">提款金額 USD</label>
        <input class="form-input" v-model="amount" placeholder="請輸入提款金額" />
      </div>
      <div class="form-item">
        <label class="form-label">國家</label>
        <input class="form-input" v-model="fiatCountry" placeholder="" />
      </div>
      <div class="form-item">
        <label class="form-label">姓名</label>
        <input class="form-input" v-model="curBank.userName" placeholder="" />
      </div>
      <!-- <div class="form-item">
        <label class="form-label">收款人地址</label>
        <input class="form-input" v-model="curBank.userName" placeholder="" />
      </div> -->
      <div class="form-item">
        <label class="form-label">銀行名稱</label>
        <input class="form-input" v-model="curBank.bankName" placeholder="" />
      </div>
      <div class="form-item">
        <label class="form-label">銀行分行</label>
        <input class="form-input" v-model="curBank.bankBranch" placeholder="" />
      </div>
      <div class="form-item">
        <label class="form-label">銀行卡帳戶</label>
        <input class="form-input" v-model="curBank.cardNumber" placeholder="" />
      </div>
      <!-- <div class="form-item">
        <label class="form-label">金融卡ABA碼</label>
        <input class="form-input" v-model="fiatABACode" placeholder="" />
      </div>
      <div class="form-item">
        <label class="form-label">金融卡號</label>
        <input class="form-input" v-model="fiatCardNumber" placeholder="" />
      </div>
      <div class="form-item">
        <label class="form-label">銀行卡swiftCode</label>
        <input class="form-input" v-model="fiatSwiftCode" placeholder="銀行卡swiftCode" />
      </div> -->
      <div class="form-item">
        <label class="form-label">提現密码</label>
        <div class="input-group">
          <input class="form-input" v-model="password" placeholder="" type="number" />
          <!-- <button class="all-btn" @click="setAll">全部</button> -->
        </div>
      </div>
      <div class="info-row">
        <span>提現費用：{{ withdrawType?.ratio }}%</span>
        <!-- <span style="margin-left:auto;">可用餘額：{{ allAmount }}</span> -->
      </div>
      <div class="info-row">
        <span>實際到帳：{{ Number(amount) - Number(amount * withdrawType?.ratio) }}</span>
      </div>
      
      <div class="submit-btn-section">
        <button class="submit-btn" @click="submit">提交</button>
      </div>
    </div>
    <transition name="fade">
      <div v-if="showNetworkSelect" class="network-select-modal">
        <div class="network-select-mask" @click="closeNetworkSelect"></div>
        <transition name="slide-up-bottom">
          <div v-if="showNetworkSelect" class="network-select-popup-bottom">
            <div class="network-select-header">
              <span>請選擇</span>
              <svg class="close-btn" @click="closeNetworkSelect" width="24" height="24" viewBox="0 0 24 24"><path d="M6 6l12 12M6 18L18 6" stroke="#888" stroke-width="2" stroke-linecap="round"/></svg>
            </div>
            <div class="network-select-list">
              <div v-for="item in networkOptions" :key="item.value" class="network-select-item" @click="selectNetwork(item.value)">
                <span>{{ item.label }}</span>
                <img :src="selectedNetwork === item.value ? currentIcon : noCuttemdIcon" class="network-check-icon" />
              </div>
            </div>
          </div>
        </transition>
      </div>
    </transition>
    <transition name="fade">
      <div v-if="showCoinSelect" class="network-select-modal">
        <div class="network-select-mask" @click="closeCoinSelect"></div>
        <transition name="slide-up-bottom">
          <div v-if="showCoinSelect" class="network-select-popup-bottom">
            <div class="network-select-header">
              <span>請選擇</span>
              <svg class="close-btn" @click="closeCoinSelect" width="24" height="24" viewBox="0 0 24 24"><path d="M6 6l12 12M6 18L18 6" stroke="#888" stroke-width="2" stroke-linecap="round"/></svg>
            </div>
            <div class="network-select-list">
              <div v-for="item in coinOptions" :key="item.value" class="network-select-item" @click="selectCoin(item.value)">
                <div style="display:flex;align-items:center;gap:10px;">
                  <img :src="item.icon" class="coin-icon" alt="coin" />
                  <span>{{ item.label }}</span>
                </div>
                <img :src="selectedCoin === item.value ? currentIcon : noCuttemdIcon" class="network-check-icon" />
              </div>
            </div>
          </div>
        </transition>
      </div>
    </transition>
  </div>
</template>

<script setup>
import {DIFF_ISFREEZE, DIFF_WITHDRAW} from '@/config/index'
import {useFreeze} from '@/hook/useFreeze'

const {_isFreeze} = useFreeze()
import { computed, ref } from 'vue'
import currentIcon from '@/assets/defi/current.png'
import noCuttemdIcon from '@/assets/defi/noCuttemd.png'
import {useMainStore} from '@/store/index.js'
import {useToast} from '@/hook/useToast'
import {useUserStore} from '@/store/user/index'
import {showToast} from 'vant'
import {
  getBindCardList,
  haveCacheAddress,
  getCacheStatus,
  saveCacheAddress,
  withdrawSubmit
} from '@/api/account.js'
import {useRoute, useRouter} from 'vue-router'
import {filterCoin2} from '@/utils/public'
import {priceFormat} from '@/utils/decimal.js'

const route = useRoute()
const router = useRouter()

const mainStore = useMainStore()
const {_toast} = useToast()
const userStore = useUserStore()
userStore.getUserInfo()
// 用户信息
const {userInfo} = storeToRefs(userStore)
// 用户余额信息
const {asset} = storeToRefs(userStore)

const activeTab = ref(0)
const networkOptions = ref([
  { label: 'TRC20', value: 'USDT-TRC' },
  { label: 'ERC20', value: 'USDT-ERC' },
  
])
const selectedNetwork = ref(networkOptions.value[1].value) // 默认ERC20
const showNetworkSelect = ref(false)

const coinOptions = [
  { label: 'USDT', value: 'usdt', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/public/1e8deac3f3e547629a8bf2b466dc0359.png' },
  { label: 'ETH', value: 'eth', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/public/ede2393ae55247b686b96c38231d4676.png' },
  { label: 'USDC', value: 'usdc', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/LOGOIPSUM/c0830db57f39487aa4a1205ff23c1633.png' },
  { label: 'BTC', value: 'btc', icon: 'https://xinyuanimg-c.oss-cn-hongkong.aliyuncs.com/LOGOIPSUM/c0830db57f39487aa4a1205ff23c1633.png' },
]
const selectedCoin = ref(coinOptions[0].value) // 默认USDT
const showCoinSelect = ref(false)

const address = ref('')
const amount = ref('')

const allAmount = computed(() => {
  let data = 0
  // debugger
  //银行卡提现--> 显示对应币种资产 无则默认显示 usdt资产
  const index = activeTab.value == 1 && asset.value.findIndex(item => filterCoin2(item.symbol) == curBank.value.coin?.toLowerCase())

  //查询余额
  for (let i = 0; i < asset.value.length; i++) {
    // 银行卡提现
    if (activeTab.value == 1) {

      if (
          asset.value[i].type == 1 &&
          filterCoin2(asset.value[i].symbol) == (index != -1 ? curBank.value.coin?.toLowerCase() : 'usdt')
      ) {
        data = asset.value[i].availableAmount
        selectedCoin.value = (index != -1 ? curBank.value.coin : 'usdt')
      }

    } else {
      // 币种提现
      if (asset.value[i].type == 1 && filterCoin2(asset.value[i].symbol) == selectedCoin.value) {
        data = asset.value[i].availableAmount
      }
    }
  }
  return data
})



const withdrawType = computed(() => {
  let data = {}
  if (activeTab.value == 1) {
    data = mainStore.getWithdrawList.find((item) => item.rechargeType == "jpy" && item.rechargeName == "BANK")
  } else {
    data = mainStore.getWithdrawList.find((item) => item.rechargeType == selectedCoin.value && item.rechargeName ==selectedNetwork.value)
  }
  return data
})
console.log(withdrawType.value)


// 法币tab表单
const fiatAmount = ref('')
const fiatCountry = ref('')
const fiatName = ref('')
const fiatAddress = ref('')
const fiatBankName = ref('')
const fiatBankAddress = ref('')
const fiatBankType = ref('')
const fiatABACode = ref('')
const fiatCardNumber = ref('')
const fiatSwiftCode = ref('')

function openNetworkSelect() {
  showNetworkSelect.value = true
}
function closeNetworkSelect() {
  showNetworkSelect.value = false
}
function selectNetwork(val) {
  selectedNetwork.value = val
  closeNetworkSelect()
}
function openCoinSelect() {
  showCoinSelect.value = true
}
function closeCoinSelect() {
  showCoinSelect.value = false
}
function selectCoin(val) {
  selectedCoin.value = val
  networkOptions.value = []
  if (selectedCoin.value == 'usdt') {
    networkOptions.value = [
      { label: 'TRC20', value: 'USDT-TRC' },
      { label: 'ERC20', value: 'USDT-ERC' }
    ]
  } else {
    networkOptions.value = [
      { label: val.toUpperCase(), value: val.toUpperCase() },
    ]
  }
  selectedNetwork.value = networkOptions.value[0].value
  closeCoinSelect()
}
function setAll() {
  amount.value = allAmount.value
}
const password = ref('')
const submitForm = () => {
  userStore.getUserInfo()
  let flag = true
  // 非空判断
  if (amount.value == '' || amount.value > allAmount.value || amount.value <= 0) {
    // showToast('请输入正确的提现数量')
    _toast('withdraw_please_num')
    return
  }
  if (activeTab.value == 0) {
    if (address.value == '') {
      // showToast('请输入提现地址')
      _toast('withdraw_please_address')
      return
    }
  }
  if (password.value == '') {
    // showToast('请输入提现密码')
    _toast('withdraw_please_pwd')
    return
  }
  if (userInfo.value.detail?.userTardPwd == null) {
    // showToast('请设置资金密码')
    flag = false
    _toast('withdraw_please_fundPwd')
    setTimeout(() => {
      router.push('/fund-password')
    }, 800)
    return
  }

  // if (['paxpay'].includes(__config._APP_ENV) && amount.value > 500) {
  //   flag = false
  //   if (advancedAuth.value !== '1') {
  //     _toast('please_advanced')
  //     setTimeout(() => {
  //       router.push('/certification-advanced')
  //     }, 1000)
  //     // return
  //   } else {
  //     flag = true
  //   }
  // }
  let params = ``
  if (activeTab.value == 1) {
    params = `amount=${priceFormat(amount.value)}&coinType=BANK&pwd=${password.value}&adress=${
        curBank.value.cardNumber
    }&coin=usdt&bankName=${curBank.value.bankName}&bankUserName=${
        curBank.value.userName
    }&bankBranch=${curBank.value.bankBranch}`
  } else {
    params = `amount=${priceFormat(amount.value)}&coinType=${selectedNetwork.value}&pwd=${
        password.value
    }&adress=${address.value}&coin=${selectedCoin.value}`
  }
  if (flag) {
    if (DIFF_WITHDRAW.includes(__config._APP_ENV)) {
      getCacheStatus().then((res) => {
        if (!res.data) {
          setAddress(params)
        } else {
          _toast('last_order_info')
        }
      })
    } else {
      submitApi(params)
    }
  }
}
const setAddress = (params) => {
  let data = {coin: selectedNetwork.value, address: address.value}
  saveCacheAddress(data).then((res) => {
    if (res.code == '200') {
      submitApi(params)
    }
  })
}
const submitApi = (params) => {
  withdrawSubmit(params).then((res) => {
    if (res.code == '200') {
      // showToast('提现成功')
      _toast('withdraw_success')
      // 提交成功
      setTimeout(() => {
        // router.push('/withdraw')
        router.push('finance-record')
      }, 500)
    } else {
      showToast(res.msg)
    }
  })
}
const submit = () => {
  // if (DIFF_ISFREEZE.includes(__config._APP_ENV)) {
  //   if (_isFreeze(DIFF_ISFREEZE)) {
  //     submitForm()
  //   }
  // } else {
    submitForm()
  // }
}

// 银行卡数据
const curBank = ref({})
const showSheet = ref(false)
const selectSheet = (item) => {
  showSheet.value = false
  curBank.value = item
}
// 获取银行卡信息
const hideBank = (item) => {
  let str = ''
  var str1 = item.substring(0, 4)
  var str2 = item.substring(item.length - 4, item.length)
  str = str1 + ' *** *** ' + str2
  return str
}

const bankList = ref([])
const getCardList = async () => {
  const res = await getBindCardList()
  if (res.code == '200') {
    if (res.data.length > 0) {
      bankList.value = res.data
      curBank.value = bankList.value[0]
    } else {
      // showToast('请先绑定银行卡')
      _toast('Unbound_bank_card')
      setTimeout(() => {
        router.push('/bind-card')
      }, 1000)
    }
  }
}
// getCardList()
</script>

<style scoped>
.withdraw-apply-container {
  background: #f5f7fa;
  min-height: 100vh;
  padding: 0;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
}
.withdraw-tabs {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 24px 0 18px 0;
  gap: 18px;
  margin-left: 16px;
}
.tab {
  font-size: 18px;
  font-weight: 600;
  color: #222;
  padding: 7px 22px;
  border-radius: 999px;
  background: none;
  cursor: pointer;
  transition: background 0.18s, color 0.18s;
}
.tab.active {
  background: #000;
  color: #fff;
}
.tab-content {
  padding: 0 16px;
}
.form-item {
  margin-bottom: 18px;
}
.form-label {
  font-size: 14px;
  color: #222;
  font-weight: 600;
  margin-bottom: 6px;
  display: block;
}
.form-value {
  background: #fff;
  border-radius: 24px;
  padding: 12px 18px;
  font-size: 14px;
  color: #222;
  display: flex;
  align-items: center;
  min-height: 44px;
}
.select-value {
  justify-content: flex-start;
  cursor: pointer;
}
.coin-value {
  gap: 8px;
}
.coin-select-trigger {
  cursor: pointer;
}
.coin-icon {
  width: 20px;
  height: 20px;
  margin-right: 6px;
}
.input-group {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 24px;
  padding: 0 0 0 0;
}
.form-input {
  width: 100%;
  border: none;
  background: #fff;
  border-radius: 24px;
  padding: 12px 18px;
  font-size: 14px;
  color: #222;
  outline: none;
  min-height: 44px;
  box-sizing: border-box;
  margin-bottom: 0;
}
.all-btn {
  background: #000;
  color: #fff;
  border: none;
  border-radius: 16px;
  font-size: 13px;
  font-weight: 600;
  padding: 6px 18px;
  margin-right: 10px;
  margin-left: 8px;
  cursor: pointer;
  transition: background 0.18s;
}
.info-row {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #222;
  margin-bottom: 6px;
  margin-top: 2px;
}
.submit-btn-section {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 32px 0 24px 0;
  background: #f5f7fa;
  position: sticky;
  bottom: 0;
  z-index: 10;
}
.submit-btn {
  width: 90%;
  max-width: 460px;
  height: 48px;
  background: #000;
  color: #fff;
  border: none;
  border-radius: 999px;
  font-size: 18px;
  font-weight: 600;
  letter-spacing: 2px;
  cursor: pointer;
  transition: background 0.2s;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
}
.submit-btn:active {
  background: #222;
}
/* Network select modal styles */
.network-select-modal {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  z-index: 1000;
}
.network-select-mask {
  position: absolute;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0,0,0,0.08);
  z-index: 1;
}
.network-select-popup-bottom {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100vw;
  background: #f5f7fa;
  border-top-left-radius: 18px;
  border-top-right-radius: 18px;
  box-shadow: 0 -2px 24px rgba(0,0,0,0.08);
  z-index: 2;
  padding-bottom: 18px;
  padding-top: 8px;
  max-width: 100vw;
}
.network-select-header {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: 600;
  color: #222;
  padding: 18px 0 10px 0;
  position: relative;
}
.network-select-header .close-btn {
  position: absolute;
  right: 18px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
}
.network-select-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 0 0 0 0;
}
.network-select-item {
  background: #fff;
  border-radius: 999px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 15px;
  color: #222;
  padding: 14px 24px;
  margin: 0 18px;
  cursor: pointer;
  box-shadow: 0 1px 4px rgba(0,0,0,0.01);
  transition: background 0.15s;
}
.network-select-item:active {
  background: #f0f0f0;
}
.network-check-icon {
  width: 20px;
  height: 20px;
}
/* 动画样式 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.25s cubic-bezier(.4,0,.2,1);
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
.fade-enter-to, .fade-leave-from {
  opacity: 1;
}
.slide-up-bottom-enter-active, .slide-up-bottom-leave-active {
  transition: transform 0.28s cubic-bezier(.4,0,.2,1), opacity 0.28s cubic-bezier(.4,0,.2,1);
}
.slide-up-bottom-enter-from, .slide-up-bottom-leave-to {
  transform: translateY(100%);
  opacity: 0;
}
.slide-up-bottom-enter-to, .slide-up-bottom-leave-from {
  transform: translateY(0);
  opacity: 1;
}
.fiat-balance-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  border-radius: 24px;
  padding: 16px 22px;
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 18px;
}
.fiat-currency {
  color: #222;
}
.fiat-balance {
  color: #222;
  font-size: 14px;
  font-weight: 400;
}
.fiat-info-row {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #222;
  margin-bottom: 18px;
  margin-top: 8px;
  padding: 0 2px;
}
</style> 